package com.zcily.demo.config;

import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.List;

@Configuration
@EnableSwagger2WebMvc
@Profile({"dev", "local"})
public class Knife4jConfig {

    @Bean(value = "dockerBean")
    public Docket dockerBean() {
        //指定使用Swagger2规范
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        .description("# Knife4j Restful APIs") //描述字段支持Markdown语法
                        .termsOfServiceUrl("https://conggege325-github-io.pages.dev/")
                        .contact("conggege325@qq.com")
                        .version("1.0")
                        .build()
                )
                .groupName("demo") //分组名称
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.zcily.demo.controller")) //这里指定Controller扫描包路径
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(CollectionUtils.newArrayList(securityScheme())) // 添加安全方案
                .securityContexts(CollectionUtils.newArrayList(securityContext())); // 添加安全上下文
        return docket;
    }

    private SecurityScheme securityScheme() {
        return new ApiKey("LoginToken", "Authorization", "header");
    }

    private SecurityContext securityContext() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.any())
                .build();
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return CollectionUtils.newArrayList(new SecurityReference("LoginToken", authorizationScopes));
    }
}
